package com.hitales.ma.jvmdemo.ast;

import com.github.javaparser.JavaParser;
import com.github.javaparser.ParseResult;
import com.github.javaparser.ParserConfiguration;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;
import com.github.javaparser.ast.body.VariableDeclarator;

public class ASTDemo {
    public static void main(String[] args) {
        String code = """
            class HelloWorld {
                void greet() {
                    int a = 10;
                    System.out.println(a);
                }
            }
            """;
        //解析器配置命名, 然后尽量的链式赋值
        ParserConfiguration config = new ParserConfiguration()
                .setLanguageLevel(ParserConfiguration.LanguageLevel.JAVA_15);
        //而解析器的构造方法支持无参和有参两种构造方式
        JavaParser parser = new JavaParser(config);

        /**
         * 而解析的结果泛型的必要性是什么
         * 我们首先看一下编译结果的返回
         */
        ParseResult<CompilationUnit> result = parser.parse(code);
        if (result.isSuccessful() && result.getResult().isPresent()) {
            CompilationUnit cu = result.getResult().get();
            cu.findAll(VariableDeclarator.class).forEach(var -> {
                System.out.println("变量名: " + var.getName());
                System.out.println("初始值表达式: " + var.getInitializer().get());
            });
            cu.findAll(ClassOrInterfaceDeclaration.class).forEach(c -> {
                System.out.println("Class name: " + c.getName());
            });
            System.out.println(cu);
        } else {
            System.out.println("解析失败！");
            result.getProblems().forEach(System.out::println);
        }
    }
}


